<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 14:39
 */

namespace frontend\controllers;
use backend\models\Baseconfigs;
use backend\models\Baseorders;
use backend\models\Baseproducts;
use backend\models\DurationPermission;
use backend\models\PackItem;
use backend\models\PackPlayer;
use backend\models\PlayerCurrencyRecordTbl;
use backend\models\PlayerTbl;
use backend\common\PubService;
use backend\services\OderService;
use backend\services\PayService;
use backend\services\ProcedureService;
use yii;

class PayController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * @return array
     * yii2 可以不屏蔽的函数
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [
                            'confirm-pay',
                            'order-list',
                            'order-builder',
                            'notify',
                            'ali-pay-notify',
                            'pack-ali-pay-notify',
                            'return-result-url',
                            'apple-notify-url',
                            'products',
                            'updated-services',
                            'order-preview',
                            'huawei-pay-notify',
                            'test',
                            'fenfun',
                            'xiaomi-pay-notify',
                            'detail',
                            'kwx',
                        ],
                        'allow' => true,
                    ],
                ],
            ],
        ];
    }

    public function actionKwx()
    {
        echo 1111;die;
    }

    /**
     * @return string
     * /Pay/ConfirmPay/1025?userid=71758
     * 前往支付首页（商品id--玩家id）
     */
    public function actionConfirmPay()
    {
        $pid = yii::$app->request->get('id');
        $userid = yii::$app->request->get('userid');
        if (empty($pid) || empty($userid)){
            return $this->redirect('/site/error');
        }
        $product = Baseproducts::find()->where(['ProductId'=>$pid])->one();
        $user = PlayerTbl::find()->where(['PlayerID'=>$userid])->one();
        if (empty($product) || empty($user)){
            return $this->redirect('/site/error');
        }
        //判断是否微信进入
        $is_wx  =  PubService::isWeChat();
        $openid = '';
        if ($is_wx){
            $pub = new PayService();
            $openid = $pub->GetOpenid($pid, $userid);
        }
        $data = [
            'product' => $product,//商品信息
            'user' => $user,
            'openid' => $openid
        ];
        $payType = Baseconfigs::findOne(['CfgKey'=>'pay_type']);
        if (empty($payType) || empty($payType->CfgVal)){//0 原生api  1：银河api
            return $this->renderPartial('index',$data);//微信H5支付原始接口方法
        }else{
            return $this->renderPartial('index-yinhe',$data);//银河api接口
        }
    }


    /**
     * @return string
     * 查看订单
     */
    public function actionOrderList()
    {
        $userid = yii::$app->request->get('userid');
        $page = max(1,yii::$app->request->get('page'));
        $order = new Baseorders();
        $list = $order->getOrderList($userid, $page);
        $total = $order->getOrderNum($userid);
        $page_size = yii::$app->params['pageSize'];
        $page_count = ceil($total / $page_size); // 计算得出总页数
        $data = [
            'userid' => $userid,
            'page' => $page,
            'list' => $list,
            'total' => $total,
            'list' => $list,
            'page_count' => $page_count
        ];
        return $this->renderPartial('order-list', $data);
    }

    /**
     * 通用下订单接口
     * ProductId  UserId  ClassId  ClientId  OpenId
     */
    public function actionOrderBuilder()
    {
        if (yii::$app->request->isPost){
            $data = yii::$app->request->post();
            $orderService = new OderService();
            $res = $orderService->checkInfo($data);
            //应用yii2的消息队列Redis处理高并发下的排队充值
            //$redis = yii::$app->redis;
            //$redis->lpush('weibo_lists',json_encode($weibo_info));
            //echo $redis->lpop('weibo_list');
            if ($res['statusCode'] == 1){
                $orderId = $res['OrderId'];//订单生成返回订单编号
                $pay = new PayService();
                $result = $pay->orderPay($orderId, $data['ClassId'], $data['OpenId']);
                return $this->renderJson($result);
            }else{
                return $this->renderJson($res);
            }
        }else{
            return $this->renderJson(['statusCode'=>300, 'message'=>'警告！非法操作']);
        }
    }


    /**
     * 通用支付同步返回地址
     */
    public function actionReturnResultUrl()
    {
        if (yii::$app->request->isPost){
            $data = yii::$app->request->post();
            $out_trade_no = $data['out_trade_no'];
            $order = Baseorders::find()->where(['OrderId'=>$out_trade_no])->one();
            return $this->renderJson($order);
        }else{
            $out_trade_no = yii::$app->request->get('out_trade_no');
            $order = Baseorders::find()->where(['OrderId'=>$out_trade_no])->one();
            $user = PlayerTbl::find()->where(['PlayerID'=>$order['UserId']])->one();
            $product = Baseproducts::find()->where(['ProductId'=>$order['ProductId']])->one();
            $data = [
                'order' => $order,
                'user' => $user,
                'product' => $product
            ];
            return $this->renderPartial('return-url',$data );
        }
    }


    /**
     * @return string
     * 微信支付回调地址
     */
    public function actionNotify()
    {
        $params = yii::$app->params;
        $xml = PayService::notify();
        $data = PayService::FromXml($xml);
        $data_sign = $data['sign'];
        unset($data['sign']);
        $sign = PayService::getSign($data, $params['wxpay_config']['key']);
        yii::getLogger()->log('kwx-money->' . print_r($data, true), yii\log\Logger::LEVEL_ERROR);
        // 判断签名是否正确  判断支付状态
        if ( ($sign === $data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS') ) {
            $payService = new PayService();
            $result = $payService->getNotifyResult($data, 0);
        }else{
            $result = false;
        }
        // 返回状态给微信服务器
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        die();
    }


    /**
     * 支付宝异步回调地址
     * @return string
     */
    public function actionAliPayNotify()
    {
        $data = $_REQUEST;
        $payService = new PayService();
        $result = $payService->getNotifyResult($data, 1);
        return $result;
    }


    /**
     * @return array
     * 苹果支付回调地址
     *@param string $receipt 收到的数据
     *@param boolean $isSandbox 是否是沙盒模式,true,false
     */
    public function actionAppleNotifyUrl()
    {
        $data = yii::$app->request->post();
        $order_id = $data['OrderId'];
        $user_id = $data['UserId'];
        $receipt = $data['receipt-data'];
        if (empty($order_id) || empty($user_id) || empty($receipt)){
            return $this->renderJson(['statusCode' => 300, 'message' => '非法参数']);
        }
        if (strlen($receipt) < 20){
            return $this->renderJson(['statusCode' => 300, 'message' => '非法参数']);
        }
        // 请求验证
        $html = PayService::apple_curl($receipt);
        $data = json_decode($html,true);

        // 如果是沙盒数据 则验证沙盒模式
        if($data['status'] == '21007'){
            // 请求验证
            $html = PayService::apple_curl($receipt, 1);
            $data = json_decode($html,true);
            $data['sandbox'] = '1';
        }
        $order = Baseorders::findOne(['OrderId' => $order_id, 'UserId' => $user_id]);
        if(empty($order) || ($order->PayStatus > 0)){
            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
        }
        //订单中购买金币的数量和充值次数/订单表的支付状态
        $product = Baseproducts::findOne(['ProductId' => $order->ProductId]);
        $playTbl = PlayerTbl::findOne(['PlayerID' => $user_id]);
        if (!$playTbl || !$product)return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
        $coin_dia_num = $product->NumCount;
        $classId = $product->ClassId;
        // 判断是否购买成功
        if(intval($data['status']) === 0){
            //更新数据库
            $transaction = Yii::$app->db->beginTransaction();
            if ($product->ClassId < 2){//金币和钻石充值
                try {
                    if ($classId === 0){//钻石充值
                        $typestate = 'Diamond';
                        $p_coin = $playTbl->Diamond;
                    }elseif ($classId === 1){//金币充值
                        $typestate = 'GoldCoin';
                        $p_coin = $playTbl->GoldCoin;
                    }else{
                        $typestate = 'GoldCoin';
                        $p_coin = $playTbl->GoldCoin;
                    }
                    $nowNum = $p_coin + $coin_dia_num;
                    $rechargeTime = $playTbl->RechargeTimes;
                    $service = new PayService();
//              首次充值金币或者钻石时，赠送10个钻石
                    $productId = $order->ProductId;
                    if (empty($rechargeTime) && ($productId < 2000)){
                        if ($classId === 0){//钻石充值
                            $nowNum = $nowNum + 10;
                        }elseif($classId === 1){//金币充值
                            $p_coin = $playTbl->Diamond;
                            $goldNum = $p_coin + 10;
                            PlayerTbl::updateAll(['Diamond' => $goldNum],'PlayerID = :PlayerID',[':PlayerID'=>$user_id]);
                        }
                        $sevState = $service->writeRecord($order_id);
                        if ($sevState == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
                        }
                    }
//              首次充值金币或者钻石时，赠送20000金币
//                if (empty($rechargeTime)){
//                    if ($classId === 0){
//                        $p_coin = $playTbl->GoldCoin;
//                        $goldNum = $p_coin + 20000;
//                        PlayerTbl::updateAll(['GoldCoin' => $goldNum],'PlayerID = :PlayerID',[':PlayerID'=>$user_id]);
//                    }elseif($classId === 1){
//                        $nowNum = $nowNum + 20000;
//                    }
//                    $sevState = $service->writeRecord($order_id);
//                    if ($sevState == false){
//                        return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
//                    }
//                }
                    //首次充值任意金币时，赠送20000金币
//                $isgive = $playTbl->isGive;
//                if (empty($isgive) && $classId == 1){
//                    $nowNum = $nowNum + 20000;
//                    $sevState = $service->writeRecord($order_id);
//                    PlayerTbl::updateAll(['isGive' => 1],'PlayerID = :PlayerID',[':PlayerID'=>$user_id]);
//                    if ($sevState == false){
//                        return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
//                    }
//                }

                    //代理提点分成---【只对购买钻石类型进行分成】
                    if (empty($classId)){
                        $proservice = new ProcedureService();
                        $result = $proservice->buildProcedure($order_id);
                        if ($result['status'] <> 1){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
                        }
                    }
                    //开启额外赠送
                    $extracount = 0;
                    $extrascale = 0;
                    if ($product->ExtraScale > 0){//额外比例
                        $pecal = $product->ExtraScale;
                        $ncont = $product->NumCount;
                        $extrascale = $ncont * $pecal;
                        $stat = $service->writeExtraRecord($order_id, $extrascale, 1);
                        if ($stat == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
                        }
                    }
                    if ($product->ExtraCount > 0){//额外个数
                        $extracount = $product->ExtraCount;
                        $stat = $service->writeExtraRecord($order_id, $extracount, 2);
                        if ($stat == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
                        }
                    }
                    $nowNum = $nowNum + $extrascale + $extracount;
                    PlayerTbl::updateAll([$typestate => $nowNum, 'RechargeTimes' => $rechargeTime + 1],'PlayerID = :PlayerID',[':PlayerID'=>$user_id]);
                    //判断transaction_id是否已经存在-数据库新增transaction_id字段
                    Baseorders::updateAll(['PayStatus'=>1, 'PayDate'=>date('Y-m-d H:i:s',time())], 'OrderId = :OrderId', [':OrderId' => $order_id]);
                    $service->writeRecord($order_id);
                    $transaction->commit();
                    return $this->renderJson(['statusCode' => 200, 'message' => '充值成功', 'data' => $order_id]);
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
                }
            }elseif ($product->ClassId == 2){//道具类支付购买
                try {
                    $userId = $order->UserId;
                    $product = Baseproducts::findOne(['ProductId'=>$order->ProductId]);
                    $packitemid = $product->PackId;
                    $amount = $order->NumCount;
                    $packitem = PackItem::findOne(['id'=>$packitemid]);
                    if ($packitem->classify_id == 2){//id=2 为纪念币类型
                        //写入玩家道具记录表pack_player [同类别的累加]
                        $packplayer = PackPlayer::findOne(['item_id'=>$packitemid ,'user_id' => $userId]);
                        $pamount = 0;
                        if ($packplayer){
                            $pamount = $packplayer->amount;
                            $packplayer->amount = $amount + $pamount;
                        }else{
                            $packplayer = new PackPlayer();
                            $packplayer->user_id = $userId;
                            $packplayer->item_id = $packitemid;
                            $packplayer->amount = $amount;
                        }
                        $packplayer->save();
                    }elseif (($packitem->classify_id == 6) || ($packitem->classify_id == 7)){//id=6/7 为普通月卡/至尊月卡类型
                        $permission = DurationPermission::findOne(['user_id'=>$order->UserId]);
                        if ($permission){
                            if ($packitem->classify_id == 6){//id=6 为普通月卡(30天共计720小时)
                                $end_time = $permission->ordinary_end_time;
                                if ($end_time < time()){
                                    $permission->ordinary_start_time = time();
                                    $permission->ordinary_end_time = time() + 3600*720;
                                }else{
                                    $permission->ordinary_end_time = $end_time + 3600*720;
                                }
                            }
                            if ($packitem->classify_id == 7){//id=7 为至尊月卡
                                $end_time = $permission->super_end_time;
                                if ($end_time < time()){
                                    $permission->super_start_time = time();
                                    $permission->super_end_time = time() + 3600*720;
                                }else{
                                    $permission->super_end_time = $end_time + 3600*720;
                                }
                            }
                        }else{
                            $permission = new DurationPermission();
                            $permission->user_id = $order->UserId;
                            if ($packitem->classify_id == 6){//id=6 为普通月卡
                                $permission->ordinary_start_time = time();
                                $permission->ordinary_end_time = time() + 3600*720;
                            }
                            if ($packitem->classify_id == 7){//id=7 为至尊月卡
                                $permission->super_start_time = time();
                                $permission->super_end_time = time() + 3600*720;
                            }
                        }
                        $permission->save();
                    }
                    //写入购买记录
                    $playcurrency = new PlayerCurrencyRecordTbl();
                    $playcurrency->playerId = $userId;
                    $playcurrency->typeId = 3;//道具类型为3
                    $playcurrency->Currency = $amount;
                    $playcurrency->beforeCurrency = empty($pamount) ? 0 : $pamount;
                    $playcurrency->afterCurrency = empty($pamount) ? $amount : ($amount + $pamount);
                    $playcurrency->Comments = '购买背包道具：'.$packitem['name'].',数量：'.$amount;
                    $playcurrency->recordDate = date('Y-m-d H:i:s', time());
                    $playcurrency->AddrIp = PubService::real_ip();
                    $playcurrency->adminId = 1;
                    $playcurrency->save();
                    //支付成功 修改订单状态
                    $order->PayStatus = 1;
                    $order->PayDate = date('Y-m-d H:i:s', time());
                    $order->save();
                    $transaction->commit();
                    return $this->renderJson(['statusCode' => 200, 'message' => '充值成功', 'data' => $order_id]);
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
                }
            }
        }
        return $this->renderJson(['statusCode' => 300, 'message' => '充值失败', 'data' => $order_id]);
    }

    /**
     * @return array
     * 某一种类别下所有商品的列表
     */
    public function actionProducts()
    {
        $id = yii::$app->request->get('id');
        $type = yii::$app->request->get('type');
        $tejia = yii::$app->request->get('tejia');
        $channelid = yii::$app->request->get('channelid');
        $psts = new Baseproducts();
        $data = $psts->getProducts($id, $type, $tejia, $channelid);
        foreach ($data as $key => $val){
            $data[$key]['ProductImages'] = array(urldecode($val['ProductImages']));
            $data[$key]['Amount'] = number_format($val['Amount'],2,".","");
            $data[$key]['NumCount'] = intval($val['NumCount']);
            $data[$key]['ExtraScale'] = intval($val['ExtraScale']);
            $data[$key]['ExtraCount'] = intval($val['ExtraCount']);
            $data[$key]['SortId'] = intval($val['SortId']);
            $data[$key]['ProductId'] = intval($val['ProductId']);
        }
        $product = [
            'statusCode' => 200,
            'message' => "获取产品列表信息",
            'data' => $data,
            'exts' => 20000
        ];
        return $this->renderJson($product);
    }

    /**
     * 多个同类商品二级弹出
     */
    public function actionDetail()
    {
        $getData = yii::$app->request->get();
        $pts = new Baseproducts();
        $data = $pts->getNextChannel($getData);
        $product = [
            'statusCode' => 200,
            'message' => "获取二级产品列表信息",
            'data' => $data['data'],
            'pack' => $data['pack'],
            'exts' => 20000
        ];
        return $this->renderJson($product);
    }


    public function actionUpdatedServices()
    {
        $AppsUpdated = Baseconfigs::findOne(['CfgKey'=>'AppsUpdated']);
        $appcfg = $AppsUpdated->CfgVal;
        $appsupdated = empty($appcfg) ? false : true;
        $iOSPurchase = Baseconfigs::findOne(['CfgKey'=>'iOSPurchase']);
        $iOScfg = $iOSPurchase->CfgVal;
        $iospurchase = empty($iOScfg) ? false : true;
        $android_update_addr = Baseconfigs::findOne(['CfgKey'=>'androidwww']);
        $ios_update_addr = Baseconfigs::findOne(['CfgKey'=>'ioswww']);
        $pc_update_addr = Baseconfigs::findOne(['CfgKey'=>'pcwww']);
        $data = [
            'AppsUpdated' => $appsupdated,
            'iOSPurchase' => $iospurchase,
            'androidwww' => $android_update_addr->CfgVal,
            'ioswww' => $ios_update_addr->CfgVal,
            'pcwww' => $pc_update_addr->CfgVal,
        ];
        return $this->renderJson($data);
    }


    public function actionOrderPreview()
    {
        $pid = yii::$app->request->get('id');
        if (empty($pid)){
            return $this->redirect('/site/error');
        }
        $product = Baseproducts::find()->where(['ProductId'=>$pid])->one();
        if (empty($product)){
            return $this->redirect('/site/error');
        }
//        //判断是否微信进入
//        $is_wx  =  PubService::isWeChat();
//        $openid = '';
//        if ($is_wx){
//            $pub = new PayService();
//            $openid = $pub->get_shopping_openid($pid);
//        }
        $shopping_url = yii::$app->params['shopping_url'].'?id='.$pid;
        //判断是否微信进入
        $is_wx  =  PubService::isWeChat();
        $openid = '';
        $playtbl = [];
        if ($is_wx){
            $pub = new PayService();
            $info = $pub->get_user_info($shopping_url);
            $accId = $info['unionid'];
            $openid = $info['openid'];
            $playtbl = PlayerTbl::findOne(['AccID'=>$accId]);
            $playtbl = empty($playtbl) ? [] : $playtbl;
        }
        $data = [
            'product' => $product,//商品信息
            'openid' => $openid,
            'playtbl' => $playtbl,
        ];
        $payType = Baseconfigs::findOne(['CfgKey'=>'pay_type']);
        if (empty($payType) || empty($payType->CfgVal)){//0 原生api  1：银河api
            return $this->renderPartial('order-preview',$data);//微信H5支付原始接口方法
        }else{
            return $this->renderPartial('order-preview-yinhe',$data);//银河api接口
        }
    }


    /**
     * @return array
     * 华为支付回调地址
     *@param string
     *@param boolean
     */
    public function actionHuaweiPayNotify()
    {
        if (yii::$app->request->isGet){
            return $this->renderJson(['statusCode' => 300, 'message' => '非法操作']);
        }
        $data = yii::$app->request->post();
        $result = $data['result'];
        $requestId = $data['requestId'];
        $order = Baseorders::findOne(['RequestId' => $requestId]);
        if (!empty($result)){
            return $this->renderJson(['statusCode' => 300, 'message' => '支付失败']);
        }
        if (empty($requestId)){
            return $this->renderJson(['statusCode' => 300, 'message' => '非法参数']);
        }
        if ($order->Amount != $data['amount']){
            return $this->renderJson(['statusCode' => 300, 'message' => '支付失败']);
        }
        // 判断是否购买成功
        if(intval($data['result']) === 0) {
            //更新数据库
            if (empty($order) || ($order->PayStatus > 0)) {
                return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
            }
            //订单中购买金币的数量和充值次数/订单表的支付状态
            $product = Baseproducts::findOne(['ProductId' => $order->ProductId]);
            $playTbl = PlayerTbl::findOne(['PlayerID' => $order->UserId]);
            $coin_dia_num = $product->NumCount;
            $classId = $product->ClassId;
            $transaction = Yii::$app->db->beginTransaction();
            if ($product->ClassId < 2) {//金币和钻石充值
                try {
                    if ($classId === 0){//钻石充值
                        $typestate = 'Diamond';
                        $p_coin = $playTbl->Diamond;
                    }elseif ($classId === 1){//金币充值
                        $typestate = 'GoldCoin';
                        $p_coin = $playTbl->GoldCoin;
                    }else{
                        $typestate = 'GoldCoin';
                        $p_coin = $playTbl->GoldCoin;
                    }
                    $nowNum = $p_coin + $coin_dia_num;
                    $rechargeTime = $playTbl->RechargeTimes;
                    $service = new PayService();
//              首次充值金币或者钻石时，赠送10个钻石
                    $productId = $order->ProductId;
                    if (empty($rechargeTime) && ($productId < 2000)){
                        if ($classId === 0){//钻石充值
                            $nowNum = $nowNum + 10;
                        }elseif($classId === 1){//金币充值
                            $p_coin = $playTbl->Diamond;
                            $goldNum = $p_coin + 10;
                            PlayerTbl::updateAll(['Diamond' => $goldNum],'PlayerID = :PlayerID',[':PlayerID'=>$order->UserId]);
                        }
                        $sevState = $service->writeRecord($order->OrderId);
                        if ($sevState == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    //代理提点分成---【只对购买钻石类型进行分成】
                    if (empty($classId)){
                        $proservice = new ProcedureService();
                        $result = $proservice->buildProcedure($order->OrderId);
                        if ($result['status'] <> 1){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    //开启额外赠送
                    $extracount = 0;
                    $extrascale = 0;
                    if ($product->ExtraScale > 0){//额外比例
                        $pecal = $product->ExtraScale;
                        $ncont = $product->NumCount;
                        $extrascale = $ncont * $pecal;
                        $stat = $service->writeExtraRecord($order->OrderId, $extrascale, 1);
                        if ($stat == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    if ($product->ExtraCount > 0){//额外个数
                        $extracount = $product->ExtraCount;
                        $stat = $service->writeExtraRecord($order->OrderId, $extracount, 2);
                        if ($stat == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    $nowNum = $nowNum + $extrascale + $extracount;
                    PlayerTbl::updateAll([$typestate => $nowNum, 'RechargeTimes' => $rechargeTime + 1],'PlayerID = :PlayerID',[':PlayerID'=>$order->UserId]);
                    //判断transaction_id是否已经存在-数据库新增transaction_id字段
                    Baseorders::updateAll(['PayStatus'=>1, 'PayDate'=>date('Y-m-d H:i:s',time())], 'OrderId = :OrderId', [':OrderId' => $order->OrderId]);
                    $service->writeRecord($order->OrderId);
                    $transaction->commit();
                    return $this->renderJson(['statusCode' => 200, 'message' => '充值成功', 'data' => $order->OrderId]);
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                }
            }elseif ($product->ClassId == 2){//道具类支付购买
                try {
                    $userId = $order->UserId;
                    $product = Baseproducts::findOne(['ProductId'=>$order->ProductId]);
                    $packitemid = $product->PackId;
                    $amount = $order->NumCount;
                    $packitem = PackItem::findOne(['id'=>$packitemid]);
                    if ($packitem->classify_id == 2){//id=2 为纪念币类型
                        //写入玩家道具记录表pack_player [同类别的累加]
                        $packplayer = PackPlayer::findOne(['item_id'=>$packitemid ,'user_id' => $userId]);
                        $pamount = 0;
                        if ($packplayer){
                            $pamount = $packplayer->amount;
                            $packplayer->amount = $amount + $pamount;
                        }else{
                            $packplayer = new PackPlayer();
                            $packplayer->user_id = $userId;
                            $packplayer->item_id = $packitemid;
                            $packplayer->amount = $amount;
                        }
                        $packplayer->save();
                    }elseif (($packitem->classify_id == 6) || ($packitem->classify_id == 7)){//id=6/7 为普通月卡/至尊月卡类型
                        $permission = DurationPermission::findOne(['user_id'=>$order->UserId]);
                        if ($permission){
                            if ($packitem->classify_id == 6){//id=6 为普通月卡(30天共计720小时)
                                $end_time = $permission->ordinary_end_time;
                                if ($end_time < time()){
                                    $permission->ordinary_start_time = time();
                                    $permission->ordinary_end_time = time() + 3600*720;
                                }else{
                                    $permission->ordinary_end_time = $end_time + 3600*720;
                                }
                            }
                            if ($packitem->classify_id == 7){//id=7 为至尊月卡
                                $end_time = $permission->super_end_time;
                                if ($end_time < time()){
                                    $permission->super_start_time = time();
                                    $permission->super_end_time = time() + 3600*720;
                                }else{
                                    $permission->super_end_time = $end_time + 3600*720;
                                }
                            }
                        }else{
                            $permission = new DurationPermission();
                            $permission->user_id = $order->UserId;
                            if ($packitem->classify_id == 6){//id=6 为普通月卡
                                $permission->ordinary_start_time = time();
                                $permission->ordinary_end_time = time() + 3600*720;
                            }
                            if ($packitem->classify_id == 7){//id=7 为至尊月卡
                                $permission->super_start_time = time();
                                $permission->super_end_time = time() + 3600*720;
                            }
                        }
                        $permission->save();
                    }
                    //写入购买记录
                    $playcurrency = new PlayerCurrencyRecordTbl();
                    $playcurrency->playerId = $userId;
                    $playcurrency->typeId = 3;//道具类型为3
                    $playcurrency->Currency = $amount;
                    $playcurrency->beforeCurrency = empty($pamount) ? 0 : $pamount;
                    $playcurrency->afterCurrency = empty($pamount) ? $amount : ($amount + $pamount);
                    $playcurrency->Comments = '购买背包道具：'.$packitem['name'].',数量：'.$amount;
                    $playcurrency->recordDate = date('Y-m-d H:i:s', time());
                    $playcurrency->AddrIp = PubService::real_ip();
                    $playcurrency->adminId = 1;
                    $playcurrency->save();
                    //支付成功 修改订单状态
                    $order->PayStatus = 1;
                    $order->PayDate = date('Y-m-d H:i:s', time());
                    $order->save();
                    $transaction->commit();
                    return $this->renderJson(['statusCode' => 200, 'message' => '充值成功']);
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                }
            }
        }
        return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
    }

    /**
     * @return array
     * 小米支付回调地址
     *@param string
     *@param boolean
     */
    public function actionXiaomiPayNotify()
    {
        $reqparams = $_REQUEST;
        $params = array();
        $httpHelper = new PayService();
        foreach ($reqparams as $key => $value) {
            if($key != 'signature'){
                $params[$key] = $httpHelper->xiaomiurlDecode($value);
            }
        }
        $signature = $reqparams['signature'];
        $checkSign = $httpHelper->verifySignature($params, $signature);
        if($checkSign){
            //更新数据库
            $order = Baseorders::findOne(['OrderId'=>$reqparams['cpOrderId']]);
            if(empty($order) || ($order->PayStatus > 0)){
                return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
            }
            //订单中购买金币的数量和充值次数/订单表的支付状态
            $product = Baseproducts::findOne(['ProductId' => $order->ProductId]);
            $playTbl = PlayerTbl::findOne(['PlayerID' => $order->UserId]);
            $coin_dia_num = $product->NumCount;
            $classId = $product->ClassId;
            $transaction = Yii::$app->db->beginTransaction();
            if ($product->ClassId < 2){
                try {
                    if ($classId === 0){//钻石充值
                        $typestate = 'Diamond';
                        $p_coin = $playTbl->Diamond;
                    }elseif ($classId === 1){//金币充值
                        $typestate = 'GoldCoin';
                        $p_coin = $playTbl->GoldCoin;
                    }else{
                        $typestate = 'GoldCoin';
                        $p_coin = $playTbl->GoldCoin;
                    }
                    $nowNum = $p_coin + $coin_dia_num;
                    $rechargeTime = $playTbl->RechargeTimes;
                    $service = new PayService();
//              首次充值金币或者钻石时，赠送10个钻石
                    $productId = $order->ProductId;
                    if (empty($rechargeTime) && ($productId < 2000)){
                        if ($classId === 0){//钻石充值
                            $nowNum = $nowNum + 10;
                        }elseif($classId === 1){//金币充值
                            $p_coin = $playTbl->Diamond;
                            $goldNum = $p_coin + 10;
                            PlayerTbl::updateAll(['Diamond' => $goldNum],'PlayerID = :PlayerID',[':PlayerID'=>$order->UserId]);
                        }
                        $sevState = $service->writeRecord($order->OrderId);
                        if ($sevState == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    //代理提点分成---【只对购买钻石类型进行分成】
                    if (empty($classId)){
                        $proservice = new ProcedureService();
                        $result = $proservice->buildProcedure($order->OrderId);
                        if ($result['status'] <> 1){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    //开启额外赠送
                    $extracount = 0;
                    $extrascale = 0;
                    if ($product->ExtraScale > 0){//额外比例
                        $pecal = $product->ExtraScale;
                        $ncont = $product->NumCount;
                        $extrascale = $ncont * $pecal;
                        $stat = $service->writeExtraRecord($order->OrderId, $extrascale, 1);
                        if ($stat == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    if ($product->ExtraCount > 0){//额外个数
                        $extracount = $product->ExtraCount;
                        $stat = $service->writeExtraRecord($order->OrderId, $extracount, 2);
                        if ($stat == false){
                            return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                        }
                    }
                    $nowNum = $nowNum + $extrascale + $extracount;
                    PlayerTbl::updateAll([$typestate => $nowNum, 'RechargeTimes' => $rechargeTime + 1],'PlayerID = :PlayerID',[':PlayerID'=>$order->UserId]);
                    //判断transaction_id是否已经存在-数据库新增transaction_id字段
                    Baseorders::updateAll(['PayStatus'=>1, 'PayDate'=>date('Y-m-d H:i:s',time())], 'OrderId = :OrderId', [':OrderId' => $order->OrderId]);
                    $service->writeRecord($order->OrderId);
                    $transaction->commit();
                    return $this->renderJson(['statusCode' => 200, 'message' => '充值成功', 'data' => $order->OrderId]);
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                }
            }elseif ($product->ClassId == 2){
                try {
                    $userId = $order->UserId;
                    $product = Baseproducts::findOne(['ProductId'=>$order->ProductId]);
                    $packitemid = $product->PackId;
                    $amount = $order->NumCount;
                    $packitem = PackItem::findOne(['id'=>$packitemid]);
                    if ($packitem->classify_id == 2){//id=2 为纪念币类型
                        //写入玩家道具记录表pack_player [同类别的累加]
                        $packplayer = PackPlayer::findOne(['item_id'=>$packitemid ,'user_id' => $userId]);
                        $pamount = 0;
                        if ($packplayer){
                            $pamount = $packplayer->amount;
                            $packplayer->amount = $amount + $pamount;
                        }else{
                            $packplayer = new PackPlayer();
                            $packplayer->user_id = $userId;
                            $packplayer->item_id = $packitemid;
                            $packplayer->amount = $amount;
                        }
                        $packplayer->save();
                    }elseif (($packitem->classify_id == 6) || ($packitem->classify_id == 7)){//id=6/7 为普通月卡/至尊月卡类型
                        $permission = DurationPermission::findOne(['user_id'=>$order->UserId]);
                        if ($permission){
                            if ($packitem->classify_id == 6){//id=6 为普通月卡(30天共计720小时)
                                $end_time = $permission->ordinary_end_time;
                                if ($end_time < time()){
                                    $permission->ordinary_start_time = time();
                                    $permission->ordinary_end_time = time() + 3600*720;
                                }else{
                                    $permission->ordinary_end_time = $end_time + 3600*720;
                                }
                            }
                            if ($packitem->classify_id == 7){//id=7 为至尊月卡
                                $end_time = $permission->super_end_time;
                                if ($end_time < time()){
                                    $permission->super_start_time = time();
                                    $permission->super_end_time = time() + 3600*720;
                                }else{
                                    $permission->super_end_time = $end_time + 3600*720;
                                }
                            }
                        }else{
                            $permission = new DurationPermission();
                            $permission->user_id = $order->UserId;
                            if ($packitem->classify_id == 6){//id=6 为普通月卡
                                $permission->ordinary_start_time = time();
                                $permission->ordinary_end_time = time() + 3600*720;
                            }
                            if ($packitem->classify_id == 7){//id=7 为至尊月卡
                                $permission->super_start_time = time();
                                $permission->super_end_time = time() + 3600*720;
                            }
                        }
                        $permission->save();
                    }
                    //写入购买记录
                    $playcurrency = new PlayerCurrencyRecordTbl();
                    $playcurrency->playerId = $userId;
                    $playcurrency->typeId = 3;//道具类型为3
                    $playcurrency->Currency = $amount;
                    $playcurrency->beforeCurrency = empty($pamount) ? 0 : $pamount;
                    $playcurrency->afterCurrency = empty($pamount) ? $amount : ($amount + $pamount);
                    $playcurrency->Comments = '购买背包道具：'.$packitem['name'].',数量：'.$amount;
                    $playcurrency->recordDate = date('Y-m-d H:i:s', time());
                    $playcurrency->AddrIp = PubService::real_ip();
                    $playcurrency->adminId = 1;
                    $playcurrency->save();
                    //支付成功 修改订单状态
                    $order->PayStatus = 1;
                    $order->PayDate = date('Y-m-d H:i:s', time());
                    $order->save();
                    $transaction->commit();
                    return $this->renderJson(['statusCode' => 200, 'message' => '充值成功']);
                } catch (Exception $e) {
                    $transaction->rollBack();
                    return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
                }
            }
        }
        return $this->renderJson(['statusCode' => 300, 'message' => '充值失败']);
    }


}